const { adminInfo } = require('../config/config'),
      { addAdmin, login } = require('../services/Admin'),
      { makeCrypto, trimSpace, returnInfo } = require('../libs/utils'),
      { LOGIN } = require('../config/error_config');

class Admin {
    async createAdmin(ctx, next) {
        adminInfo.password = makeCrypto(adminInfo.password);
        console.log(adminInfo);
        const res = await addAdmin(adminInfo);

        if(res){
            console.log(0);
        } else {
            console.log(1);
        }
    }

    
    // 登录标识校验
    async loginCheck(ctx, next) {
        if(ctx.session && ctx.session.userInfo){
            // 登录状态
            ctx.body = returnInfo(LOGIN.LOGIN_STATUS);
            return;
        }

        // 非登录状态
        ctx.body = returnInfo(LOGIN.NOT_LOGIN_STATUS); 
    }

    // 登录接口
    async loginAction(ctx, next) {
        // 获取前端传过去的数据
        const { username, password } = ctx.request.body;
        console.log(ctx.request.body);
        // 判断用户名或密码是否存在
        if(!username || !password) {
            ctx.body = LOGIN.INVALID_OPERATION;
            return;
        }

        // 判断用户名
        if(trimSpace(username).length <= 0) {
            ctx.body = LOGIN.INVALID_USERNAME_LENGTH;
            return;
        }

        // 判断密码
        if(trimSpace(password).length <= 0) {
            ctx.body = LOGIN.INVALID_PASSWORD_LENGTH;
            return;
        }

        // 组装数据
        const userInfo = {
            username: trimSpace(username),
            password: makeCrypto(trimSpace(password)), // 加密密码
        };
        
        const res = await login(userInfo);
       
        // 未查询到用户
        if(res === 10003) {
            ctx.body = returnInfo(LOGIN.USERNAME_NOT_EXIST);
            return;
        }

        // 密码错误
        if(res === 10004) {
            ctx.body = returnInfo(LOGIN.PASSWORD_ERROR);
            return;
        }
        
        // 判断session是否存在
        if(!ctx.session.userInfo){
            ctx.session.userInfo = res;
        }
        console.log(ctx.session.userInfo);
        ctx.body = returnInfo(LOGIN.SUCCESS, ctx.session.userInfo);
    }

    // 退出登录
    async logoutAction(ctx, next) {
        // 删除session中的信息
        delete ctx.session.userInfo;

        ctx.body = returnInfo(LOGIN.LOGOUT_SUCCESS);
    }
}

module.exports = new Admin();